package com.hz.ruoyiquality.service;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hz.rouyigonggong.utils.ResultJSON;
import com.hz.ruoyiquality.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;

import java.awt.*;
import java.io.*;
@Service
@Slf4j
public class QrCodeService {
    @Autowired
    private OrderMapper orderMapper;
    private static final String UPLOAD_URL = "http://192.168.149.73:8080/app/seller/common/upload"; // 你的文件上传接口地址

//    public static void main(String[] args) {
//        Integer orderNo = 54;  // 修改为 Integer 类型
//        String qrUrl = generateAndUploadQr(orderNo);
//        if (qrUrl != null) {
//            System.out.println("二维码上传成功，访问路径：" + qrUrl);
//            saveToDatabase(orderNo, qrUrl);
//        }
//    }

    /**
     * 生成二维码并上传
     */
    public  String generateAndUploadQr(Integer orderNo) {
        try {
            // 1. 生成二维码
            byte[] qrBytes = generateQrCode(orderNo);
            if (qrBytes == null) {
                return null;
            }

            // 2. 转换为 MultipartFile 并上传
            MultipartFile multipartFile = new MockMultipartFile(
                    "file", // 字段名称
                    orderNo + ".jpg", // 文件名，Integer 直接拼接字符串
                    "image/jpeg", // MIME 类型
                    qrBytes // 文件字节内容
            );
            return uploadFile(multipartFile);
        } catch (Exception e) {
            log.error("二维码生成或上传失败", e);
            return null;
        }
    }

    /**
     * 生成二维码（返回字节数组）
     */
    public  byte[] generateQrCode(Integer orderNo) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 订单二维码内容
            String qrContent = "https://yourwebsite.com/order?orderNo=" + orderNo; // Integer 直接拼接

            // 配置二维码
            QrConfig config = new QrConfig();
            config.setWidth(500);
            config.setHeight(500);
            config.setBackColor(0xFFFFFFFF); // 白色
            config.setErrorCorrection(ErrorCorrectionLevel.H);

            // 生成二维码到输出流
            QrCodeUtil.generate(qrContent, config, "jpg", outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            log.error("二维码生成失败", e);
            return null;
        }
    }

    /**
     * 调用 Spring Boot 文件上传接口上传二维码
     */
    public  String uploadFile(MultipartFile file) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 构造请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", file.getResource());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 调用上传接口
            ResponseEntity<ResultJSON<String>> response = restTemplate.exchange(
                    UPLOAD_URL, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<ResultJSON<String>>() {}
            );

            // 打印完整的返回信息
            System.out.println("Response Body: " + response.getBody());

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                ResultJSON<String> result = response.getBody();
                System.out.println("返回的 JSON: " + result); // 打印返回数据

                if (result.getCode() == 200) {
                    return result.getData(); // 获取 OSS 文件 URL
                }
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
        }
        return null;
    }


    /**
     * 模拟将二维码 URL 存入数据库
     */
    public  void saveToDatabase(Integer orderNo, String qrUrl) {
        int rows = orderMapper.insertQrCode(orderNo, qrUrl);
        if (rows > 0) {
            System.out.println("订单：" + orderNo + "，二维码已存入数据库：" + qrUrl);
        } else {
            System.out.println("存入数据库失败！");
        }

        // 这里可以用 MyBatis 或 JPA 存入数据库
        System.out.println("订单：" + orderNo + "，二维码 URL：" + qrUrl + " 已存入数据库！");
    }
}
